import { updateNodeId, replaceNodeId, verifyAllCompletion, getAllParentNodes, getTitle, getAllWorkstepName, setNodeHasStartNode } from '@/views/bpmn/utility/utility';

export const types = {
	SHOW_SPEAK_WAIT: 'workflow/SHOW_SPEAK_WAIT',
	HIDE_SPEAK_WAIT: 'workflow/HIDE_SPEAK_WAIT',
	SHOW_CONFIRM_INFO: 'workflow/SHOW_CONFIRM_INFO',
	HIDE_CONFIRM_INFO: 'workflow/HIDE_CONFIRM_INFO',
	ADD_WORK_STEP: 'workflow/ADD_WORK_STEP',
	// eslint-disable-next-line camelcase
	update_TaskId: 'workflow/update_taskId',
	SET_CURRENT_SHOW_NODE: 'workflow/SET_CURRENT_SHOW_NODE',
	RESET_CURRENT_SHOW_NODE: 'workflow/RESET_CURRENT_SHOW_NODE',
	UPDATE_NODE_ID: 'workflow/UPDATE_NODE_ID',
	REPLACE_NODE_ID: 'workflow/REPLACE_NODE_ID',
	REMOVE_WORK_STEP: 'workflow/REMOVE_WORK_STEP',
	SET_UPDATED_NEXT_STEPS: 'workflow/SET_UPDATED_NEXT_STEPS',
	SET_START_NODE: 'workflow/SET_START_NODE',
	SET_WORK_STEPS: 'workflow/SET_WORK_STEPS',
	RESET_WORKFLOW_STATE: 'workflow/RESET_WORKFLOW_STATE',
	SET_FORM_IDS: 'workflow/SET_FORM_IDS',
	UPDATE_BREAK_RULE_STATUS: 'workflow/UPDATE_BREAK_RULE_STATUS',
	SET_BREAK_RULE_NODES: 'workflow/SET_BREAK_RULE_NODES',
	SET_IS_VIEW_FLOW: 'workflow/SET_IS_VIEW_FLOW',
	SET_TEMPLATE_NAME: 'workflow/SET_TEMPLATE_NAME',
	RESET_TEMPLATE_NAME: 'workflow/RESET_TEMPLATE_NAME',
	RESET_ALL_TEMPLATE_NAME: 'workflow/RESET_ALL_TEMPLATE_NAME',
	SET_SUMMARY_SOUCRE: 'workflow/SET_SUMMARY_SOUCRE',
	SET_LOCAL_EDITWORKSTEP: 'workflow/SET_LOCAL_EDITWORKSTEP',
	VERIFY_INVALID_ARIABLE: 'workflow/VERIFY_INVALID_ARIABLE',
	SET_AI_TEMPLATE_MODE: 'workflow/SET_AI_TEMPLATE_MODE'
};

export default {
	namespaced: true,
	state: {
		isShowConfirmInfo: false,
		isShowSpeakWait: false,
		curShowNode: '',
		taskId: '',
		worksteps: {},
		changedNextSteps: {},
		startNode: '',
		globalWorkFlow: {},
		formIds: [],
		allTemplateName: [],
		isViewFlow: false,
		breakRuleNodes: [], // 扫码失败/扫码超时的流程分支中查阅等待节点
		editWorkStep: {}, //当前正在编辑的节点详情（可用于后续缓存不同AI属性下的数据回显问题）
		aiMode: ''
	},
	mutations: {
		[types.SHOW_CONFIRM_INFO](state, taskId) {
			state.isShowConfirmInfo = true;
			state.taskId = taskId;
		},
		[types.HIDE_CONFIRM_INFO](state) {
			state.isShowConfirmInfo = false;
		},
		[types.SHOW_SPEAK_WAIT](state, taskId) {
			state.taskId = taskId;
			state.isShowSpeakWait = true;
		},
		[types.SET_FORM_IDS](state, formIds) {
			state.formIds = formIds || [];
		},
		[types.HIDE_SPEAK_WAIT](state) {
			state.isShowSpeakWait = false;
		},
		[types.ADD_WORK_STEP](state, step) {
			console.log('###ADD_WORK_STEP###', state, step);
			let data = state.worksteps;
			data[step.no] = step;
			state.worksteps = { ...data };
		},
		[types.SET_CURRENT_SHOW_NODE](state, taskId) {
			state.curShowNode = taskId.split('_')[0];
			state.taskId = taskId;
		},
		[types.RESET_CURRENT_SHOW_NODE](state) {
			console.log('###RESET_CURRENT_SHOW_NODE###', state);
			state.curShowNode = '';
			state.taskId = '';
		},
		[types.UPDATE_NODE_ID](state, node) {
			let data = state.worksteps;
			const step = data[node.parentId];
			if (step) {
				// || step.requestLocation
				updateNodeId(step.scanCode || step, node);
				state.worksteps = { ...data };
			}
		},
		[types.REPLACE_NODE_ID](state, node) {
			let data = state.worksteps;
			let step = data[node.parentId];
			if (step) {
				replaceNodeId(step.scanCode || step, node);
				state.worksteps = { ...data };
			}
		},
		[types.REMOVE_WORK_STEP](state, stepId) {
			let data = state.worksteps;
			const step = data[stepId];
			if (step) {
				delete data[stepId];
			}
			// console.log('remove');
			verifyAllCompletion(data, stepId, 'REMOVE_WORK_STEP');
			state.worksteps = { ...data };
		},
		[types.SET_UPDATED_NEXT_STEPS](state, steps) {
			// 重置查阅等待节点的breakRule
			console.log('SET_UPDATED_NEXT_STEPS : ', steps);
			steps &&
				steps.steps &&
				steps.steps.map(item => {
					if (item.previous) {
						state.breakRuleNodes.map(nodes => {
							const nodesString = nodes.join(',');
							if (nodesString.includes(item.previous)) {
								nodes.map(nodeId => {
									if (nodeId.includes('waitingRead')) {
										let data = state.worksteps;
										const step = data[nodeId];
										if (step) {
											step.breakRule = false;
											state.worksteps = { ...data };
										}
									}
								});
							}
						});
						if (
							(item.previous.includes('messageSure') ||
								item.previous.includes('ivvr') ||
								item.previous.includes('speakWaiting') ||
								item.previous.includes('detectLivingFace') ||
								item.previous.includes('faceCompare') ||
								item.previous.includes('messageCollect') ||
								item.previous.includes('silentWating') ||
								item.previous.includes('requestLocation') ||
								item.previous.includes('scanCode') ||
								item.previous.includes('sendMessage') ||
								item.previous.includes('signContract') ||
								item.previous.includes('idCardCompare') ||
								item.previous.includes('sendForm') ||
								item.previous.includes('optionJudge') ||
								item.previous.includes('sendContents') ||
								item.previous.includes('nlp') ||
								item.previous.includes('llm') ||
								item.previous.includes('soundReception') ||
								item.previous.includes('variableJudge')) &&
							item.current
						) {
							let data = state.worksteps;
							console.log('####SET_UPDATED_NEXT_STEPS');
							verifyAllCompletion(data, '', 'VERIFY_MESSAGE_SUMMARY');
							state.worksteps = { ...data };
						}
					}
				});

			let data = setNodeHasStartNode(state.worksteps, state.startNode);
			state.worksteps = { ...data };
			console.log('###save next step', state.worksteps);
		},
		[types.SET_START_NODE](state, startNode) {
			state.startNode = startNode;
		},
		[types.SET_WORK_STEPS](state, steps) {
			state.worksteps = steps || {};
		},
		[types.RESET_WORKFLOW_STATE](state) {
			// console.log('reset');
			state.isShowConfirmInfo = false;
			state.isShowSpeakWait = false;
			state.taskId = '';
			state.formIds = [];
			state.curShowNode = '';
			state.worksteps = {};
			state.changedNextSteps = {};
			state.startNode = '';
			state.allTemplateName = [];
		},
		[types.UPDATE_BREAK_RULE_STATUS](state, node) {
			let data = state.worksteps;
			let step = data[node.id];
			if (step) {
				step.breakRule = node.breakRule;
				state.worksteps = { ...data };
			}
		},
		[types.SET_BREAK_RULE_NODES](state, nodes) {
			state.breakRuleNodes = [...nodes];
		},
		[types.SET_IS_VIEW_FLOW](state, status) {
			state.isViewFlow = status;
		},
		[types.SET_TEMPLATE_NAME](state, templateName) {
			if (templateName) {
				state.allTemplateName = [...state.allTemplateName, templateName];
			}
		},
		[types.RESET_TEMPLATE_NAME](state, taskId) {
			if (state.worksteps[taskId] && state.worksteps[taskId].name) {
				state.allTemplateName = state.allTemplateName.filter(name => name !== state.worksteps[taskId].name);
			}
		},
		[types.RESET_ALL_TEMPLATE_NAME](state, templatesName) {
			state.allTemplateName = templatesName;
		},
		[types.SET_SUMMARY_SOUCRE](state, messageSummarySource) {
			state.messageSummarySource = messageSummarySource;
		},
		[types.VERIFY_INVALID_ARIABLE](state) {
			let data = state.worksteps;

			verifyAllCompletion(data, '', 'VERIFY_INVALID_ARIABLE');

			state.worksteps = { ...data };
		},
		[types.SET_AI_TEMPLATE_MODE](state, aiMode) {
			state.aiMode = aiMode;
		}
	},
	actions: {
		showConfirmInfo({ commit }, taskId) {
			commit(types.SHOW_CONFIRM_INFO, taskId);
		},
		hideConfirmInfo({ commit }) {
			commit(types.HIDE_CONFIRM_INFO);
		},
		showSpeakWait({ commit }, taskId) {
			commit(types.SHOW_SPEAK_WAIT, taskId);
		},
		hideSpeakWait({ commit }) {
			commit(types.HIDE_SPEAK_WAIT);
		},
		addWorkStep({ commit }, step) {
			commit(types.SET_TEMPLATE_NAME, step.name || '');
			commit(types.ADD_WORK_STEP, step);
		},
		setCurShowNode({ commit }, taskId) {
			commit(types.RESET_TEMPLATE_NAME, taskId);
			commit(types.SET_CURRENT_SHOW_NODE, taskId);
		},
		resetCurShowNode({ commit }) {
			commit(types.RESET_CURRENT_SHOW_NODE);
		},
		// node = {parentId, type, no}
		updateNodeId({ commit }, node) {
			commit(types.UPDATE_NODE_ID, node);
		},
		// node = {parentId, oldId, newId}
		relaceNodeId({ commit }, node) {
			commit(types.REPLACE_NODE_ID, node);
		},
		removeWorkStep({ commit }, stepId) {
			commit(types.RESET_TEMPLATE_NAME, stepId);
			commit(types.REMOVE_WORK_STEP, stepId);
		},
		setUpdatedNextSteps({ commit }, steps) {
			commit(types.SET_UPDATED_NEXT_STEPS, steps);
		},
		setStartNode({ commit }, startNode) {
			commit(types.SET_START_NODE, startNode);
		},
		setWorkSteps({ commit }, steps) {
			commit(types.SET_WORK_STEPS, steps);
		},
		setFormIds({ commit }, formids) {
			commit(types.SET_FORM_IDS, formids);
		},
		resetWorkflowState({ commit }) {
			commit(types.RESET_WORKFLOW_STATE);
		},
		updateBreakRuleStatus({ commit }, node) {
			commit(types.UPDATE_BREAK_RULE_STATUS, node);
		},
		setBreakRuleNodes({ commit }, nodes) {
			commit(types.SET_BREAK_RULE_NODES, nodes);
		},
		setViewFlow({ commit }, status) {
			commit(types.SET_IS_VIEW_FLOW, status);
		},
		setTemplateName({ commit }, templateName) {
			commit(types.SET_TEMPLATE_NAME, templateName);
		},
		resetTemplateName({ commit }, templateName) {
			commit(types.RESET_TEMPLATE_NAME, templateName);
		},
		resetAllTemplateName({ commit }, templatesName) {
			commit(types.RESET_ALL_TEMPLATE_NAME, templatesName);
		},
		setMessageSummarySource({ commit }, messageSummarySource) {
			commit(types.SET_SUMMARY_SOUCRE, messageSummarySource);
		},
		verifyInvalidVariables({ commit }) {
			commit(types.VERIFY_INVALID_ARIABLE);
		},
		setAiTemplateMode({ commit }) {
			commit(types.SET_AI_TEMPLATE_MODE);
		}
	},
	getters: {
		messageSummarySource: (state, getters) => {
			const parentNotes = getAllParentNodes(state.worksteps, state.taskId);
			let sures = [];
			let nodes = Array.from(new Set(parentNotes));
			if (nodes.includes(state.startNode)) {
				nodes = nodes.sort((a, b) => {
					return Number(a.split('_')[1]) > Number(b.split('_')[1]) ? 1 : -1;
				});
				console.log('getMessageSummaryOption : ', state.taskId, nodes);
				nodes.map(item => {
					// && state.worksteps[item].hasStartNode
					if (
						item.includes('messageSure') ||
						item.includes('ivvr') ||
						item.includes('speakWaiting') ||
						item.includes('detectLivingFace') ||
						item.includes('faceCompare') ||
						item.includes('messageCollect') ||
						item.includes('silentWating') ||
						item.includes('requestLocation') ||
						item.includes('scanCode') ||
						item.includes('sendMessage') ||
						item.includes('signContract') ||
						item.includes('idCardCompare') ||
						item.includes('sendForm') ||
						item.includes('optionJudge') ||
						item.includes('sendContents') ||
						item.includes('nlp') ||
						item.includes('soundReception') ||
						item.includes('variableJudge') ||
						item.includes('sendDeposition') ||
						item.includes('sendSign') ||
						item.includes('variableCollection') ||
						item.includes('llm')
					) {
						const option = { node: item, name: getTitle(item) };
						sures.push(option);
					}
				});
			}
			return sures;
		},
		// 查阅信息来源选择的扫码模块
		waitingReadOptionSource(state, getters) {
			let waiting = [];
			let result = getAllParentNodes(state.worksteps, state.taskId);
			const steps = getAllWorkstepName(state.worksteps);
			/** 筛选包含扫码模块的父节点 */
			steps.forEach(item => {
				if ((item.taskId.includes('scanCode') || item.taskId.includes('messageSummary')) && result.includes(item.taskId) > -1 && item.completed) {
					waiting.push(item);
				}
			});
			return waiting;
		}
	}
};
